package com.hopu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hopu.domain.Role;
import com.hopu.domain.User;
import com.hopu.entity.ResponseEntity;
import com.hopu.service.IUserService;
import com.hopu.utils.AliUtils;
import com.hopu.utils.ShiroUtils;
import com.hopu.utils.UUIDUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.jws.soap.SOAPBinding;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/user")
@RequiresRoles("root")
public class UserController {
    @Autowired
    private IUserService userService;


    //跳转用户列表页面
    @RequiresPermissions("user:list")
    @RequestMapping("/tolistPage")
    public String touserList(){
        return "admin/user/user_list";
    }

    //返回用户列表信息
   @ResponseBody
   @RequiresPermissions("user:list")
   @RequestMapping("/list")
    public IPage<User> userList(int page, int limit,User user,Model model){
       Page<User> page1 = new Page<User>(page,limit);
       QueryWrapper<User> queryWrapper = new QueryWrapper<>(new User());
       if (user!=null){
           if (!StringUtils.isEmpty(user.getUserName()))queryWrapper.like("user_name",user.getUserName());
           if (!StringUtils.isEmpty(user.getEmail()))queryWrapper.like("email",user.getEmail());
           if (!StringUtils.isEmpty(user.getTel()))queryWrapper.like("tel",user.getTel());
       }
       IPage<User> userIPage = userService.page(page1,queryWrapper);
       return userIPage;
   }

    //跳转添加用户界面
   @RequestMapping("/toAddPage")
   @RequiresPermissions("user:add")
    public String toAddPage(){
        return "admin/user/user_add";
   }
    //添加用户
   @RequestMapping("/save")
   @RequiresPermissions("user:add")
   @ResponseBody
    public ResponseEntity save(User user){
       QueryWrapper<User> objectQueryWrapper = new QueryWrapper<>();
       objectQueryWrapper.eq("user_name", user.getUserName());
       User one = userService.getOne(objectQueryWrapper);
       if (one!=null){
           return ResponseEntity.error("用户名已经存在");
       }
       user.setId(UUIDUtils.getID());
       user.setSalt(UUIDUtils.getID());
       ShiroUtils.encPass(user);
       user.setCreateTime(new Date());

       userService.save(user);
       return ResponseEntity.success("添加用户成功");
   }
   @RequestMapping("/upload")
   @ResponseBody
   public ResponseEntity upload(@RequestParam("file") MultipartFile userImg){
       String originalFilename = userImg.getOriginalFilename();
       int lastIndexOf = originalFilename.lastIndexOf(".");
       String suffix = originalFilename.substring(lastIndexOf);
       String fileName = UUID.randomUUID().toString()+suffix;
       try {
           AliUtils.uploadAli(userImg.getBytes(),fileName);
       } catch (IOException e) {
           e.printStackTrace();
       }
       HashMap<String, String> map = new HashMap<>();
       map.put("url",fileName);
       return ResponseEntity.success("图片上传成功",map);
   }

    //跳转更新用户界面
    @RequestMapping("/toUpdatePage")
    @RequiresPermissions("user:update")
    public String toUpdatePage(String id ,Model model){
        User user = userService.getOne(new QueryWrapper<User>().eq("id", id));
        model.addAttribute("user",user);
        return "admin/user/user_update";
    }
    //更新用户
    @RequestMapping("/update")
    @RequiresPermissions("user:update")
    @ResponseBody
    public ResponseEntity update(User user ){
        ShiroUtils.encPass(user);
        user.setUpdateTime(new Date());
        userService.updateById(user);
        return ResponseEntity.success("修改信息成功");
    }
    //删除用户
    @RequestMapping("/delete")
    @RequiresPermissions("user:delete")
    @ResponseBody
    public ResponseEntity delete(@RequestBody List<User> users){
        try {
            List<String> list = new ArrayList<String>();
            for (User user : users) {
                if ("root".equals(user.getUserName())) {
                    throw new Exception("root账号不能被删除");
                }
                list.add(user.getId());
            }
            userService.removeByIds(list);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.error(e.getMessage());
        }
        return ResponseEntity.success();
    }

    //跳转设置用户角色界面
    @RequestMapping("/toSetRole")
    @RequiresPermissions("user:setRole")
    public String toSetRole(String id, Model model){
        model.addAttribute("user_id", id);
        return "admin/user/user_setRole";
    }
    /**
     * 设置角色
     */
    @ResponseBody
    @RequestMapping("setRole")
    @RequiresPermissions("user:setRole")
    public ResponseEntity setRole(String id, @RequestBody ArrayList<Role> roles){
        userService.setRole(id, roles);
        return ResponseEntity.success();
    }
}
